<?php
/**
 * API文档及调试控制器
 */
namespace Api\Controller;
use Api\Library\ErrorCode;
use Api\Library\ErrorMsg;
use Api\Library\Helper;
use Api\Library\Response;

class IndexController extends ApiController{
    static $apiList;  //整个项目的所有接口

    protected function _initialize() {
        parent::_initialize();
        self::setApiList();
    }

    public function test(){
        if(!isset(Helper::$ajax['name'])){
            Response::getInstance()->setReply('code', ErrorCode::ErrorParam);
            Response::getInstance()->setReply('msg', ErrorMsg::ErrorParam);
        }else{
            Response::getInstance()->setReply('data', Helper::$ajax['name']);
        }
        $this->ajaxReturn(Helper::$param);
    }


    /**
     * 接口文档
     */
    public function index(){
        $this->display();
    }

    public function apiList(){
        $this->assign(['apiList'=>self::$apiList])->display();
    }

    /**
     * api接口调试页
     * @author  doogie
     */
    public function apiTest() {
        $do = I('get.do', '');
        $apiDetail = [
            'title' => self::$apiList[$do]['title'],
            'url' => self::$apiList[$do]['url'],
            'parameters' => self::$apiList[$do]['parameters'],
            'method' => 'POST',
            'dataType' => 'JSON'
        ];
        $this->assign(['data'=>$apiDetail, 'key'=>C('RECEPT_KEY')])->display();
    }

    /**
     * 新增一个控制器只需要在此添加即可
     * 第一层数组的键与U函数中的do参数都遵循命名规范： controller_action
     */
    private function setApiList(){
        self::$apiList = [
            'index_test' => [
                'name' => 'index_test',
                'title' => '测试接口',
                'url' => self::$server.'/api/index/test',
                'do' => U('apiTest', ['do'=>'index_test']),
                'parameters' => ['name']
            ],
            'user_registerpost' => [
                'name' => 'user_registerpost',
                'title' => '用户注册',
                'url' => self::$server . '/api/user/registerpost',
                'do' => U('apiTest', ['do' => 'user_registerpost']),
                'parameters' => ['username', 'password', 'mobile', 'idcard', 'blankcard']
            ],
            'user_loginpost' => [
                'name' => 'user_loginpost',
                'title' => '用户登入',
                'url' => self::$server . '/api/user/loginpost',
                'do' => U('apiTest', ['do' => 'user_loginpost']),
                'parameters' => ['username', 'password']
            ],
            'user_logoutpost' => [
                'name' => 'user_logoutpost',
                'title' => '用户注销',
                'url' => self::$server . '/api/user/logoutpost',
                'do' => U('apiTest', ['do' => 'user_logoutpost']),
                'parameters' => []
            ],
        ];
    }

}